//
//  HQWkWebViewController.m
//  PerfectLifeTwo
//
//  Created by 黄华强 on 2018/2/27.
//  Copyright © 2018年 PerfectLife. All rights reserved.
//

#import "HQWkWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>

@interface HQWkWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic,strong) WKWebView *wkWebView;//网页视图
@property (nonatomic,strong) UIProgressView *progressView;//进度条

@end

@implementation HQWkWebViewController

#pragma mark - 视图生命周期相关方法

- (void)dealloc {
    
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置界面
    [self createUI];
    
}

- (void)createUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.wkWebView];
    
    [self.view addSubview:self.progressView];
    
    
}

#pragma mark - 事件方法


//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(title))] && object == self.wkWebView) {
        
        self.navigationItem.title = self.wkWebView.title;
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - WKScriptMessageHandler

//拦截执行网页中的JS方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容);
    //找到对应js端的方法名,获取messge.body
    if ([message.name isEqualToString:@"shareUrl"]) {
        
        NSLog(@"%@", message.body);
        
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    //添加注入js方法, oc与js端对应实现
//    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"shareUrl"];
    
    
    if (self.htmlString) {
        //禁止用户选择
        [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
        [webView evaluateJavaScript:@"document.activeElement.blur();" completionHandler:nil];
        // 适当增大字体大小
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '250%'" completionHandler:nil];
    }
    

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    NSURL *URL = navigationAction.request.URL;
    NSLog(@"--------%@-----------",URL);
    
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

//callJS可以实现回传，在需要的类调用这个方法即可
- (void)callJS:(NSString *)jsMethod handler:(void (^)(id _Nullable))handler {
    
    [self.wkWebView evaluateJavaScript:jsMethod completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if (handler) {
            handler(response);
        }
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 懒加载

- (WKWebView *)wkWebView {
    
    if (!_wkWebView) {
        
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc] init];
        
        Configuration.preferences = [[WKPreferences alloc] init];
        Configuration.preferences.minimumFontSize = 10;
        Configuration.preferences.javaScriptEnabled = YES;
        Configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        Configuration.userContentController = [[WKUserContentController alloc] init];
        Configuration.processPool = [[WKProcessPool alloc] init];
        [Configuration.userContentController addScriptMessageHandler:self name:@"shareUrl"];
        
        
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:Configuration];
        _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
        // 设置代理
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
        //kvo title
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(title)) options:0 context:nil];
        //开启手势触摸
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
        [_wkWebView sizeToFit];
        
        if (self.htmlString) {
            
            self.htmlString = [NSString stringWithFormat:@"<div style=\"text-align:justify; text-justify:inter-ideograph;\">%@",self.htmlString];
            
            [_wkWebView loadHTMLString:self.htmlString baseURL:nil];
            
        } else if (self.url) {
            [_wkWebView loadRequest:[NSURLRequest requestWithURL:self.url]];
            
        } else {
            
        }
        
        
    }
    
    return _wkWebView;
}

- (UIProgressView *)progressView {
    
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        
        _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 3);
        
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor blackColor];
    }
    
    return _progressView;
}


@end
